# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItem
from scrapy.exporters import CsvItemExporter
from scrapy.pipelines.files import FilesPipeline


class ScraperDBPipeline:

    def __init__(self):
        pass


class ScraperCsvPipeline:

    def __init__(self, fields_to_export):
        self.file = None
        self.fields_to_export = fields_to_export

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            fields_to_export=crawler.settings.get('FIELDS_TO_EXPORT')
        )

    def open_spider(self, spider):
        self.file = open(spider.name + '.csv', 'wb')
        self.exporter = CsvItemExporter(self.file, encoding='utf-8-sig',
                                        fields_to_export=self.fields_to_export)
        print(self.exporter.fields_to_export)
        self.exporter.start_exporting()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.file.close()


class TFilesPipeline(FilesPipeline):
    def process_item(self, item, spider):
        if item['file_urls']:
            return super().process_item(item, spider)
        else:
            raise DropItem

    def file_path(self, request, response=None, info=None):
        return '/'.join(request.url.split('/')[3:])
